﻿using GPSTrackingWebsiteManager.ClassManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class StockFileByUsername : SessionManagerPage
    {

        private void GetAllUsersByCompany(int companyId)
        {
            UsersGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByCompanyID(companyId);           
        }


        private void GetStockFilesByUsername(string Username)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.StockFilesByUsername> StockFilesByUsernameEntities = GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameProvider.GetByUsernameCompanyId(Username, objSessionManager.CompanyIDSelectedComboBox);
            GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameProvider.DeepLoad(StockFilesByUsernameEntities, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.StockFiles));

            StockFileGrid.DataSource = StockFilesByUsernameEntities;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            sdsFileType.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString; 

            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.UsersColumn.Username.ToString();
                expression.SetSortOrder("Ascending");
                this.UsersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }        

        protected void UsersGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            SessionManager objSessionManager =  (SessionManager)HttpContext.Current.Session["SessionManager"];
            GetAllUsersByCompany(objSessionManager.CompanyIDSelectedComboBox);
        }

        protected void StockFileSearch1_OnAcceptEvent(List<GridDataItem> rows)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                if (rows.Count > 0)
                {
                    if (UsersGrid.SelectedItems.Count > 0)
                    {
                        SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
                        string Username = UsersGrid.Items[UsersGrid.SelectedItems[0].ItemIndex]["Username"].Text;

                        //Log 
                        DateTime dateTransaction = DateTime.Now;
                        Int64 tick = TickManager.TickManager.GetTick(dateTransaction);

                        GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.StockFilesByUsername> StockFilesByUsernameEntities = new GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.StockFilesByUsername>();
                        GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.StockFilesByUsernameLog> StockFilesByUsernameLogEntities = new GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.StockFilesByUsernameLog>();
                        foreach (GridDataItem item in rows)
                        {
                            GPSTrackingDBV2.Entities.StockFilesByUsername StockFilesByUsernameEntity = new GPSTrackingDBV2.Entities.StockFilesByUsername();
                            
                            StockFilesByUsernameEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;
                            StockFilesByUsernameEntity.StockFileId = Convert.ToInt32(item.Cells[4].Text);
                            StockFilesByUsernameEntity.Username = Username;
                            StockFilesByUsernameEntity.LastTick = tick;

                            StockFilesByUsernameEntities.Add(StockFilesByUsernameEntity);

                            //Log
                            GPSTrackingDBV2.Entities.StockFilesByUsernameLog StockFilesByUsernameLogEntity = new GPSTrackingDBV2.Entities.StockFilesByUsernameLog();

                            StockFilesByUsernameLogEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;
                            StockFilesByUsernameLogEntity.StockFileId = Convert.ToInt32(item.Cells[4].Text);
                            StockFilesByUsernameLogEntity.Username = Username;
                            StockFilesByUsernameLogEntity.TransactionDate = dateTransaction;
                            StockFilesByUsernameLogEntity.Tick = tick;
                            StockFilesByUsernameLogEntity.SyncTransaction = SessionManager.SysnTransactionType_Insert;                          

                            Dictionary<string, string> AttribTransacion = objSessionManager.GetAttribTransaction();                            

                            StockFilesByUsernameLogEntity.TypeUserTransaction = AttribTransacion[SessionManager.AttribTransaction.TypeUserTransaction.ToString()];
                            StockFilesByUsernameLogEntity.UsernameTransaction = AttribTransacion[SessionManager.AttribTransaction.UsernameTransaction.ToString()]; ;
                            StockFilesByUsernameLogEntity.CompanyIdTransaction = objSessionManager.CompanyIDSelectedComboBox;

                            StockFilesByUsernameLogEntities.Add(StockFilesByUsernameLogEntity);
                        }


                        //Transaction
                        tm.BeginTransaction();

                            GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameProvider.Insert(tm, StockFilesByUsernameEntities);
                            GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameLogProvider.Insert(tm, StockFilesByUsernameLogEntities);

                        tm.Commit();

                        GetStockFilesByUsername(Username);
                        StockFileGrid.DataBind();

                        ResizeGrid();
                    }
                    else
                    {
                        showErrorMessage("Debe seleccionar un usuario para asociar archivos");

                        ResizeGrid();
                    }
                }
                else
                {
                    showErrorMessage("Debe seleccionar al menos un archivo de la lista");
                    ResizeGrid();
                }
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo obtener los valores del buscador");
            }

        }

        protected void StockFileSearch1_OnCancelEvent()
        {

        }
       
        protected void lbClearFiltersStockFileGrid_Click(object sender, EventArgs e)
        {
            StockFileGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in StockFileGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            
            StockFileGrid.MasterTableView.Rebind();            
        }

        protected void lbClearFiltersUsersGrid_Click(object sender, EventArgs e)
        {
            UsersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            UsersGrid.MasterTableView.Rebind();
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }
        
        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Archivos compañia ...');", true);
        }

        protected void UsersGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string Username = UsersGrid.Items[UsersGrid.SelectedItems[0].ItemIndex]["Username"].Text;

                SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
                if (objSessionManager.Items.Contains("Username"))
                    objSessionManager.Items["Username"] = Username;
                else
                    objSessionManager.Items.Add("Username", Username);
                HttpContext.Current.Session["SessionManager"] = objSessionManager;


                GetStockFilesByUsername(Username);
                StockFileGrid.DataBind();

                ResizeGrid();
            }
            catch (Exception ex)
            {                
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo seleccionar el usuario");
            }
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value) / 2;

            UsersGrid.Height = Unit.Parse(Convert.ToString(Height));
            StockFileGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        protected void StockFileGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                GPSTrackingDBV2.Entities.StockFilesByUsername StockFilesByUsernameEntity = ClassManager.InvokeEntityManager.Invoke_StockFilesByUsername_Entity(e);

                StockFilesByUsernameEntity.OriginalCompanyId = StockFilesByUsernameEntity.CompanyId;
                StockFilesByUsernameEntity.OriginalStockFileId = StockFilesByUsernameEntity.StockFileId;
                StockFilesByUsernameEntity.OriginalUsername = StockFilesByUsernameEntity.Username;               

                //Log
                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);

                SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
                GPSTrackingDBV2.Entities.StockFilesByUsernameLog StockFilesByUsernameLogEntity = new GPSTrackingDBV2.Entities.StockFilesByUsernameLog();

                StockFilesByUsernameLogEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;
                StockFilesByUsernameLogEntity.StockFileId = StockFilesByUsernameEntity.StockFileId;
                StockFilesByUsernameLogEntity.Username = StockFilesByUsernameEntity.Username;
                StockFilesByUsernameLogEntity.TransactionDate = dateTransaction;
                StockFilesByUsernameLogEntity.Tick = tick;
                StockFilesByUsernameLogEntity.SyncTransaction = SessionManager.SysnTransactionType_Delete;

                Dictionary<string, string> AttribTransacion = objSessionManager.GetAttribTransaction();

                StockFilesByUsernameLogEntity.TypeUserTransaction = AttribTransacion[SessionManager.AttribTransaction.TypeUserTransaction.ToString()];
                StockFilesByUsernameLogEntity.UsernameTransaction = AttribTransacion[SessionManager.AttribTransaction.UsernameTransaction.ToString()]; ;
                StockFilesByUsernameLogEntity.CompanyIdTransaction = objSessionManager.CompanyIDSelectedComboBox;

                //Transaction
                tm.BeginTransaction();
                    StockFilesByUsernameEntity.LastTick = tick;
                    GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameProvider.Delete(tm, StockFilesByUsernameEntity);

                    GPSTrackingDBV2.Data.DataRepository.StockFilesByUsernameLogProvider.Insert(tm, StockFilesByUsernameLogEntity);

                tm.Commit();
               
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede eliminar el registro porque el archivo se encuentra asociados a otros registros.");
            }

        }

        protected void StockFileGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            string Username = string.Empty;
            if (UsersGrid.SelectedItems.Count > 0)
            {
                Username = UsersGrid.Items[UsersGrid.SelectedItems[0].ItemIndex]["Username"].Text;
            }
               
            GetStockFilesByUsername(Username);
            
        }

       
    }
}